package com.asiainfo.heshanghui.activity;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.asiainfo.heshanghui.adapter_recyclerview.HorizontalDividerItemDecoration;
import com.asiainfo.heshanghui.adapter_recyclerview.UniversalAdapter;
import com.asiainfo.heshanghui.configs.ConstantsME;
import com.asiainfo.heshanghui.entity.ScanInfo;
import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.framework.Utils.RegularUtil;
import com.framework.Utils.ToastUtil;
import com.framework.Utils.Utils;
import com.framework.Utils.Y;
import com.framework.customviews.SwipeMenuView;
import com.framework2.base.BiuooBaseActivity;
import com.framework2.customview.TitleView;
import com.framework2.greendao.GreenDaoManager;
import com.framework2.utils.BiuooCollectionUtil;
import com.asiainfo.heshanghui.R;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 商品入库  --编辑
 */
public class EditPutInStoreGoodsActivity extends BiuooBaseActivity {
    @BindView(R.id.titleView)
    TitleView titleView;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.btnCancel)
    Button btnCancel;
    @BindView(R.id.btnCommit)
    Button btnCommit;
    @BindView(R.id.ivIcon)
    ImageView ivIcon;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvCount)
    TextView tvCount;


    private UniversalAdapter adapter;
    private ArrayList<ScanInfo> phoneList = new ArrayList<>();
    private DecimalFormat decimalFormat;
    private  ScanInfo scanInfoIntent = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_edit_putinstore_goods);
        ButterKnife.bind(this);
        Utils.setTranslucentStatus(this, true);
        Utils.setStatusBarTintColor(this,
                getResources().getColor(R.color.white));
        decimalFormat = (DecimalFormat) DecimalFormat.getInstance();
        initDB();
        initView();
        initRecyclerView();
    }


    @SuppressWarnings("unchecked")
    private void initDB() {
        if (null != getIntent().getSerializableExtra(ConstantsME.entity)) {
            scanInfoIntent = (ScanInfo) getIntent().getSerializableExtra(ConstantsME.entity);
        }
        List list = GreenDaoManager.getInstance().queryEntityList(EditPutInStoreGoodsActivity.this, ScanInfo.class);
        if (!BiuooCollectionUtil.getInstance().isEmpty(list)) {
            int lenth = list.size();
            for (int i = lenth - 1; i >= 0; i--) {
                ScanInfo scanInfoFromDB = (ScanInfo) list.get(i);
                ScanInfo scanInfo = new ScanInfo();
                if (null != scanInfoFromDB && null != scanInfoIntent && !TextUtils.equals(scanInfoFromDB.getType(), scanInfoIntent.getType())) {
                    continue;
                }
                if (null != scanInfoFromDB) {
                    scanInfo.setCount(scanInfoFromDB.getCount());
                    scanInfo.setMaxCount(scanInfoFromDB.getMaxCount());
                    scanInfo.setPrice(scanInfoFromDB.getPrice());
                    scanInfo.setIsPhone(scanInfoFromDB.getIsPhone());
                    scanInfo.setChoosed(false);
                    scanInfo.setColor(scanInfoFromDB.getColor());
                    scanInfo.setContent(scanInfoFromDB.getContent());
                    scanInfo.setImei(scanInfoFromDB.getImei());
                    scanInfo.setImgUrl(scanInfoFromDB.getImgUrl());
                    scanInfo.setName(scanInfoFromDB.getName());
                    scanInfo.setRoom(scanInfoFromDB.getRoom());
                    scanInfo.setId(scanInfoFromDB.getId());
                    scanInfo.setType(scanInfoFromDB.getType());
                    scanInfo.setTotalFee(scanInfoFromDB.getTotalFee());
                }
                if (scanInfo.getIsPhone() && !containsPhone(scanInfo) && scanInfo.getCount() > 0) {
                    phoneList.add(scanInfo);
                }
            }
        } else {
            ToastUtil.getInstance().showToast("无数据...");
            finishActivity();
        }
    }


    private boolean containsPhone(@NonNull ScanInfo scanInfo) {
        int len = phoneList.size();
        for (int i = 0; i < len; i++) {
            if (TextUtils.equals(phoneList.get(i).getImei(), scanInfo.getImei())) {
                return true;
            }
        }
        return false;
    }

    private void initView() {
        titleView.setTitle("商品入库").setRightVisible(false);
        tvCount.setText(String.format("已录入:%d台",phoneList.size()));
        if (scanInfoIntent!=null){
            tvTitle.setText(scanInfoIntent.getName());
        }
    }


    @SuppressWarnings("unchecked")
    private void initRecyclerView() {
        //第一种，简单的颜色，高度,水平分割线
        final HorizontalDividerItemDecoration horizontalDividerItemDecoration = new HorizontalDividerItemDecoration(EditPutInStoreGoodsActivity.this);
        horizontalDividerItemDecoration.setColor(this, R.color.gray);
        horizontalDividerItemDecoration.setDividerHeightPx(1);
        recyclerView.addItemDecoration(horizontalDividerItemDecoration);
        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        decimalFormat.applyPattern("0.00");
        adapter = new UniversalAdapter<ScanInfo>(EditPutInStoreGoodsActivity.this, R.layout.listitem_edit_goods, phoneList) {
            @Override
            protected void getItemView(UniversalViewHolder viewHolder, final ScanInfo info, final int position) {
                ImageView iv_icon = viewHolder.getView(R.id.iv_icon);
                try {
                    Glide.with(EditPutInStoreGoodsActivity.this).load(info.getImgUrl()).placeholder(R.mipmap.default_icon).error(R.mipmap.default_icon)
                            .priority(Priority.HIGH).into(iv_icon);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                final EditText et_price = viewHolder.getView(R.id.et_price);
                try {
                    et_price.setText(decimalFormat.format(info.getPrice()));
                    et_price.setSelection(decimalFormat.format(info.getPrice()).length());
                    et_price.addTextChangedListener(new TextWatcher() {
                        @Override
                        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

                        }

                        @Override
                        public void onTextChanged(final CharSequence s, int start, int before, int count) {
                            try {
                                Y.y("onTextChanged:" + s);
                                info.setPrice(Double.parseDouble(decimalFormat.format(Double.parseDouble(s.toString()))));
                            } catch (Exception e) {
                                info.setPrice(-1);
                            }
                        }

                        @Override
                        public void afterTextChanged(Editable s) {
                            Y.y("afterTextChanged:" + s.toString());
                            if (RegularUtil.getInstance().isAtleast3bitNumberAfterDigit(s.toString())) {
                                String temp = et_price.getText().toString();
                                et_price.setText(temp.substring(0, temp.length() - 1));
                                et_price.setSelection(et_price.getText().toString().length());
                            }
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }

                ((SwipeMenuView) viewHolder.itemView).setSwipeEnable(false);
                viewHolder.getView(R.id.editCountLayout).setVisibility(View.GONE);
                viewHolder.getView(R.id.tv_imei).setVisibility(View.VISIBLE);
                viewHolder.setText(R.id.tv_imei, String.valueOf("IMEI:" + info.getImei()));

            }
        };
        recyclerView.setAdapter(adapter);
        recyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断隐藏软键盘是否弹出
                if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                    //隐藏软键盘
                    Utils.isCloseSoftInputMethod(EditPutInStoreGoodsActivity.this, null, true);
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    /**
     * 刷新数据库数据,然后关闭
     */
    @SuppressWarnings("unchecked")
    private void refreshDBthenClose() {
        if (!BiuooCollectionUtil.getInstance().isEmpty(phoneList)) {
            int phoneLenth = phoneList.size();
            for (int i = phoneLenth - 1; i >= 0; i--) {
                if (phoneList.get(i).getPrice() < 0) {
                    ToastUtil.getInstance().showToast("价格不正确");
                    return;
                }
            }
        }
        boolean a = GreenDaoManager.getInstance().deleteAll(EditPutInStoreGoodsActivity.this, ScanInfo.class);

        if (!BiuooCollectionUtil.getInstance().isEmpty(phoneList)) {
            int phoneLenth = phoneList.size();
            for (int i = phoneLenth - 1; i >= 0; i--) {
                GreenDaoManager.getInstance().insertEntity(EditPutInStoreGoodsActivity.this, phoneList.get(i));
            }
        }
        startActivity(PutInStoreListDetailActivity.class);
        finishActivity();
    }

    @OnClick({R.id.btnCancel, R.id.btnCommit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btnCancel:
                finishActivity();
                break;
            case R.id.btnCommit:
                refreshDBthenClose();
                break;
        }
    }
}
